<?php

namespace app\home\controller;

use app\common\controller\Home;

class Post extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->PostModel = model('Post.Post');
        $this->RecordModel = model('User.Record');
        $this->UserModel = model('User.User');
    }

    // add => view => 一个页面
    public function add()
    {
        if($this->request->isPost())
        {
            /* 
                消费记录表 插入
                用户表 更新积分
                用户积分 - (悬赏积分 + 根帖子状态的所需积分)
                帖子表 插入
            */

            // 验证码验证
            $vercode = $this->request->param('vercode');

            if(!captcha_check($vercode))
            {
                $this->error('验证码错误');
            }


            // 开启事务
            $this->PostModel->startTrans();
            $this->RecordModel->startTrans();
            $this->UserModel->startTrans();

            // 悬赏积分
            $acceptPoint = $this->request->param('point',0);

            // 帖子的状态所需积分
            $state = $this->request->param('state',0);

            // 0 1 2 3 去查询相应的积分
            $StatePoint = model('Config')->where('key',"PostState{$state}")->value('value');

            // halt($StatePoint);
            $StatePoint = $StatePoint ? $StatePoint : 0;

            // 悬赏积分 + 帖子的状态所需积分 = 发帖所需积分
            $PostPoint = bcadd($acceptPoint,$StatePoint);

            // 用户的积分 - 发帖所需积分
            $UpdatePoint = bcsub($this->LoginUser['point'],$PostPoint);

            if($UpdatePoint < 0)
            {
                $this->error('积分不足，请及时充值');
            }

            // 封装更新用户积分
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $UpdatePoint
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserStatus === FALSE)
            {
                $this->error($this->UserModel->getError());
            }

            // 接收全部参数
            $params = $this->request->param();

            // 封装数据
            $PostData = [
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content'],
                'point' => $PostPoint,
                'state' => $params['state'],
                'userid' => $this->LoginUser['id']
            ];

            $PostStatus = $this->PostModel->validate('common/Post/Post')->save($PostData);

            if($PostStatus === FALSE)
            {
                $this->UserModel->rollback();
                $this->error($this->PostModel->getError());
            }

            // 消费记录
            $RecordData = [
                'point' => $PostPoint,
                'content' => "您发的帖子【{$PostData['title']}】成功，消费了{$PostPoint}积分",
                'state' => 1,
                'userid' => $this->LoginUser['id']
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError());
            }

            if($RecordStatus === FALSE || $UserStatus === FALSE || $PostStatus === FALSE)
            {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error('发布失败');
            }else{
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->success('发布成功',url('home/index/index'));
            }

        }


        // 查询分类
        $CateList = model('Post.Cate')->order('weigh','desc')->limit(7)->select();

        $StateList = $this->PostModel->state();

        return $this->fetch('',[
            'CateList' => $CateList,
            'StateList' => $StateList
        ]);
    }

    public function edit()
    {
        $postid = $this->request->param('postid',0);

        $post = $this->PostModel->find($postid);

        if(!$post)
        {
            $this->error('帖子不存在，请重新选择');
        }

        if($post['userid'] != $this->LoginUser['id'])
        {
            $this->error('您没有权限编辑他人的帖子');
        }

        if($this->request->isPost())
        {
            $params = $this->request->param();

            // if(!captcha_check($params['vercode']))
            // {
            //     $this->error('验证码错误');
            // }

            // 封装更新数据
            $data = [
                'id' => $postid,
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content']
            ];

            $result = $this->PostModel->isUpdate(true)->validate('common/Post/Post.edit')->save($data);

            if($result === FALSE)
            {
                $this->error('编辑失败');
            }else{
                $this->success('编辑成功',url('home/index/info',['postid' => $postid]));
            }
        }

        // 查询分类
        $CateList = model('Post.Cate')->order('weigh','desc')->limit(7)->select();

        $StateList = $this->PostModel->state();
        return $this->fetch('',[
            'CateList' => $CateList,
            'StateList' => $StateList,
            'post' => $post
        ]);
    }

    public function del()
    {
        if($this->request->isAjax())
        {

            $postid = $this->request->param('postid',0);

            // deletetime is null
            $post = $this->PostModel->find($postid);

            if(!$post)
            {
                $this->error('帖子不存在，无法删除');
            }

            // $result = $post->delete();
            $result = $this->PostModel->destroy($postid);

            if($result === FALSE)
            {
                $this->error('删除失败');
            }

            $this->success('删除成功',url('home/index/index'));
        }
    }
}
